/**
 * 
 */
package com.dovgopoly.carlogbook.web.login.client.presenter;

import com.dovgopoly.carlogbook.common.mvp.AbstractPresenter;
import com.dovgopoly.carlogbook.services.LoginServiceAsync;
import com.dovgopoly.carlogbook.services.exceptions.LoginRemoteException;
import com.dovgopoly.carlogbook.web.login.client.LoginEventBus;
import com.dovgopoly.carlogbook.web.login.client.view.LoginView;
import com.dovgopoly.carlogbook.web.login.client.view.LoginViewimpl;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;
import com.mvp4g.client.annotation.Presenter;

/**
 * @author Zhenya
 * 
 */
@Presenter(view = LoginViewimpl.class)
public class LoginPresenter extends AbstractPresenter<LoginView, LoginView.Presenter, LoginEventBus> implements
		LoginView.Presenter {

	@Inject
	LoginServiceAsync loginService;

	public void onStart() {
		GWT.log("Started");
	}

	@Override
	protected com.dovgopoly.carlogbook.web.login.client.view.LoginView.Presenter getPresenter() {
		return this;
	}

	public void login(String username, String password) {
		loginService.login(username, password, new AsyncCallback<Void>() {

			public void onSuccess(Void arg0) {
				GWT.log("onSuccess");

				GWT.log(GWT.getHostPageBaseURL());
				Window.Location.getHref();
				String urlToWebBoard = Window.Location.getProtocol() + "//" + Window.Location.getHost() + "/Main.html"
						+ Window.Location.getQueryString(); // Window.Location.getPath()

				Window.open(urlToWebBoard, "_self", "");
				// /Window.Location.replace(urlToWebBoard);
			}

			public void onFailure(Throwable caught) {
				GWT.log("onFailure", caught);
				if (caught instanceof LoginRemoteException) {
					view.showErrorMessage(((LoginRemoteException) caught).getMessage());
				}
			}
		});

	}

	public void showRegistrationForm() {
		eventBus.showRegistrationForm();

	}
}
